package com.chuji.crmcj.act;

import android.app.Activity;
import android.app.AlertDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chuji.crmcj.R;
import com.chuji.crmcj.utils.UIUtils;

/**
 * Created by w.pitt on 2016/3/17.
 */
public class TestAct extends Activity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener {
    private MediaPlayer mediaPlayer = null;
    private LinearLayout ll_cancel;
    private ImageButton mBtn_play;
    private SeekBar mSb_detail_play_progress;
    private TextView mTv_play_time;
    private TextView mTv_total_time;
    private int goOrPause = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_test);
        Button button = (Button) findViewById(R.id.bt);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPlayRecorderDialog();
            }
        });
    }

    //播放录音的dialog
    public void showPlayRecorderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_play_recorder, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
//        ImageView mIv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        ll_cancel = (LinearLayout) view.findViewById(R.id.ll_cancel);
        mBtn_play = (ImageButton) view.findViewById(R.id.btn_play);
        mSb_detail_play_progress = (SeekBar) view.findViewById(R.id.sb_detail_play_progress);
        mTv_play_time = (TextView) view.findViewById(R.id.tv_play_time);
        mTv_total_time = (TextView) view.findViewById(R.id.tv_total_time);
        mSb_detail_play_progress.setEnabled(false);

        //播放进度条
        mSb_detail_play_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (fromUser == true) {
                    mediaPlayer.seekTo(progress);
                    mTv_play_time.setText(ShowTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


            }
        });
        //退出播放
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mediaPlayer.stop();
            }
        });
        //点击播放
        mBtn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (goOrPause == 0) {
                    play();
                    mTv_play_time.setText(ShowTime(mSb_detail_play_progress.getProgress()));
                    int Alltime = mediaPlayer.getDuration();
                    mTv_total_time.setText(ShowTime(Alltime));
                    goOrPause = 1;
                } else if (goOrPause == 1 || goOrPause == 2) {
                    pause();

                }
            }
        });
        dialog.show();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    //当音乐播放时，每次按键时都会播放或者停止音乐
    private void pause() {
        //if(bt_pause.getText().toString().trim().equals("继续")){
        if (goOrPause == 2) {
            mediaPlayer.start();
            goOrPause = 1;
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            return;
        } else if (goOrPause == 1) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                goOrPause = 2;
                mBtn_play.setBackgroundResource(R.drawable.bofang);
            } else {
                UIUtils.showToastSafe("请先播放音频");
            }
        }
    }

    private int currentPostion;

    private void play() {

        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);


            //todo 录音地址
//            mediaPlayer.reset();
//            FileInputStream fis = new FileInputStream("http://192.168.1.222:8088/UpLoads/SoundRecord/%E5%BC%A0%E8%B5%A2-%E6%9C%89%E9%92%B1%E7%9C%9F%E5%A5%BD[68mtv.com].mp4");
//            mediaPlayer.setDataSource(fis.getFD());

            mediaPlayer.reset();
            mediaPlayer.setDataSource("http://192.168.1.222:8088/UpLoads/SoundRecord/%E5%BC%A0%E8%B5%A2-%E6%9C%89%E9%92%B1%E7%9C%9F%E5%A5%BD[68mtv.com].mp4"); // 设置数据源
            mediaPlayer.prepare(); // prepare自动播放
//            mediaPlayer.prepareAsync();
            mediaPlayer.start();
            StrartbarUpdate();
            mSb_detail_play_progress.setMax(mediaPlayer.getDuration());
            mSb_detail_play_progress.setEnabled(true);
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            //音乐播放时事件
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    mBtn_play.setEnabled(true);
                }
            });

            //出错时的事件
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mBtn_play.setEnabled(true);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            UIUtils.showToastSafe("播放失败");
        }
    }

    //时间显示函数,我们获得音乐信息的是以毫秒为单位的，把把转换成我们熟悉的00:00格式
    private String ShowTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    Handler handler = new Handler();

    private void StrartbarUpdate() {
        handler.post(r);
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            int CurrentPosition = mediaPlayer.getCurrentPosition();
            mTv_play_time.setText(ShowTime(CurrentPosition));
            mSb_detail_play_progress.setProgress(CurrentPosition);
            handler.postDelayed(r, 100);
        }
    };

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        mSb_detail_play_progress.setSecondaryProgress(percent);
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

    }
}
